# @Version        : 1.0
# @Update Time    : 2024/12/15 0:14
# @File           : github.py
# @IDE            : PyCharm
# @Desc           : github oath2登录
from fastapi_limiter.depends import RateLimiter
from fastapi_oauth20 import GitHubOAuth20, FastAPIOAuth20
from fastapi import APIRouter, Depends, Response, BackgroundTasks
from fastapi_utils.cbv import cbv
from starlette.responses import RedirectResponse
from src.core.base_controller import BaseController
from src.core.response import ResponseSchema

_github_client = GitHubOAuth20(client_id="", client_secret="")
_github_oauth2 = FastAPIOAuth20(_github_client, redirect_uri="")

router = APIRouter()


@cbv(router)
class GithubAuthController(BaseController):
    @router.get("", summary="获取 Github 授权链接", response_model=ResponseSchema)
    async def github_auth2(self):
        auth_url = await _github_client.get_authorization_url(redirect_uri="")
        return self.success(data=auth_url)

    @router.get(
        "/callback",
        summary="Github 授权自动重定向",
        description="Github 授权后，自动重定向到当前地址并获取用户信息，通过用户信息自动创建系统用户",
        dependencies=[Depends(RateLimiter(times=5, minutes=1))],
        response_model=ResponseSchema,
    )
    async def github_callback(
        self,
        response: Response,
        background_tasks: BackgroundTasks,
        oauth2: FastAPIOAuth20 = Depends(_github_oauth2),
    ):
        token, _state = oauth2
        access_token = token["access_token"]
        user_info = await _github_client.get_userinfo(access_token)
        data = await oauth2.create_user(user_info)
        # 登录成功, 返回前端登录token
        return RedirectResponse(
            url=f"{self.request.url.scheme}://{self.request.url.hostname}:{self.request.url.port}/login?access_token={data['access_token']}"
        )
